%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
clear all; close all; clc;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Modify main_str to match path on your machine
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
main_str = 'C:\Users\Marco\Dropbox\Housing_Brainstorming\Information_disclosure';
% main_str = 'L:\agargano\Dropbox\Housing_Brainstorming\Information_disclosure';

save_str = [main_str,'\Replication_code_RFS\Model'];

% gris of values of sigma_{\psi} and sigma_{\epsilon}
endowM_grid       = (0.01:0.01:0.100);
biasS_grid        = (0.000:0.020:0.100);
[m_grid1,m_grid2] = ndgrid(endowM_grid,biasS_grid);
grid_mat          = [m_grid1(:),m_grid2(:)];
n_grid            = size(grid_mat,1);

for bb = 1:n_grid

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Seller Reservation and Distribution of Private Values

    seller_reservation     = 650000;
    bidders_mean           = 650000;
    % bidders_std            = 65000;
    bidders_std            = 32500;
    bidders_logstd         = sqrt(log((bidders_std^2)/exp(2*log(bidders_mean))+1));
    bidders_logmean        = log(bidders_mean)-((bidders_logstd^2)/2);
    
    n_sim                  = 1000000; % number of random draws for bids

    start_bid_scale        = (0.75:0.010:1.25);
    start_bid              = start_bid_scale*seller_reservation; % vector of entry bids (1+alpha)*seller reservation
    n_start                = size(start_bid,2);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    mu_endow               = grid_mat(bb,1); % value of \sigma_{psi} for valuation shocks   

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    mu_b                   = 0;              % mu_{\epsilon} for valuation errors
    std_b                  = grid_mat(bb,2); % \sigma_{\epsilon} for valuation errors

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    n_bidders_all_vec      = (1:1:15); % vector of number of bidders
    i_all                  = size(n_bidders_all_vec,2);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Simulation

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Allocate Memory
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Psales_mat           = nan(i_all,n_start);
    Ebidders_mat         = nan(i_all,n_start);
    EbidderW_mat         = nan(i_all,n_start);
    EbidderW_unb_mat     = nan(i_all,n_start);
    EbidderW_obj_unb_mat = nan(i_all,n_start);    
    Esales_mat           = nan(i_all,n_start);
    Erev_mat             = nan(i_all,n_start);
 
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    poolobj         = parpool('local');
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    parfor i = 1:i_all % parallel loop over number of bidders

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        start_bid_curr   = start_bid; % entry bid vector
        bids_values_mat  = lognrnd(bidders_logmean,bidders_logstd,n_bidders_all_vec(i),n_sim); % draws of ``true'' private values
        bias_curr_mat    = exp(normrnd(mu_b-(0.5*(std_b^2)),std_b,n_bidders_all_vec(i),n_sim)); % draws of valuation errors 
        if i > 1
            [bids_values_bias_mat,sel_unb_mat] = sort(bids_values_mat.*bias_curr_mat,'descend'); % observed noisy valuations sorted
        elseif i == 1
            bids_values_bias_mat = bids_values_mat.*bias_curr_mat; % observed noisy valuations with one bidder
            sel_unb_mat          = ones(1,n_sim);
        end

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
        for k = 1:n_start   

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
            sales_succ_vec           = zeros(n_sim,1);
            bidder_value_vec         = zeros(n_sim,1);
            bidder_value_unb_vec     = zeros(n_sim,1);  
            bidder_value_obj_unb_vec = zeros(n_sim,1);               
            sales_price_vec          = nan(n_sim,1);
            nbidders_vec             = zeros(n_sim,1);            
        
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%            
            for n = 1:n_sim
    
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                bids_values_vec       = bids_values_bias_mat(:,n); % noisy valuations      
                bids_values_unb_vec   = bids_values_mat(:,n);      % ``true'' valuations            
                is_act                = bids_values_vec>start_bid_curr(k);  % which bidders have noisy private value above entry bid? 

                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                
                nbidders_vec(n,1)     = sum(is_act); % num bidders with noisy private value above entry bid (enter the auction)
                
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%     
                if nbidders_vec(n,1) == 1 % only one bidder enters
                     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                                         
                     sales_price_vec(n,1)          = start_bid_curr(k); % sales price is equal to the entry bid
                     bidder_value_vec(n,1)         = bids_values_vec(1)-start_bid_curr(k); % bidder perceived surplus
                     bidder_value_unb_vec(n,1)     = bids_values_unb_vec(sel_unb_mat(1,n))-start_bid_curr(k); % bidder ``true'' surplus (no valuation errors)
                     bidder_value_obj_unb_vec(n,1) = bidder_value_unb_vec(n,1); % bidder ``true'' surplus (no valuation errors) pre-valuation shocks                
                     sales_succ_vec(n,1)           = 1; % house is sold    
                     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                     
                elseif nbidders_vec(n,1) > 1  % multiple bidders enter  
                     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                     endow_vec                 = exprnd(mu_endow,nbidders_vec(n,1),1); % draw of exponential valuation shocks
                     bids_values_endow_vec     = bids_values_vec(1:nbidders_vec(n,1)).*(1+endow_vec); % bidders who entered have valuation impacted by valuation shocks    
                     bids_values_endow_unb_vec = bids_values_unb_vec(sel_unb_mat(1:nbidders_vec(n,1),n)).*(1+endow_vec); % impact of valuation shocks on private values with no valuation errors                        
                     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                     
                     [bids_values_endow_vec,sel_endow]         = sort(bids_values_endow_vec,'descend'); % sort perceived private values post valuation shock
                     [bids_values_endow_unb_vec,sel_unb_endow] = sort(bids_values_endow_unb_vec,'descend'); % sort ``true'' private values post valuation shock                    
                     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                     sales_price_vec(n,1)      = bids_values_endow_vec(2);  % sales price (second highest value, including valuation shock and valuation error)
                     bidder_value_vec(n,1)     = bids_values_endow_vec(1)     - sales_price_vec(n,1);  % surplus including valuation errors and valuation shocks
                     bidder_value_unb_vec(n,1) = bids_values_endow_unb_vec(1) - sales_price_vec(n,1);  % surplus excluding valuation errors, but including valuation shocks 
                     bidder_value_obj_unb_vec(n,1) = bids_values_unb_vec(sel_unb_mat(sel_unb_endow(1),n)) - sales_price_vec(n,1); % surplus excluding valuation errors and valuation shock
                     sales_succ_vec(n,1)       = 1; % house is sold  
                end    
            
            end
     
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            EbidderW_mat(i,k)         = nanmean(bidder_value_vec)/n_bidders_all_vec(i); % expected surplus, including valuation errors and valuation shocks
            EbidderW_unb_mat(i,k)     = nanmean(bidder_value_unb_vec)/n_bidders_all_vec(i); % expected surplus, excluding valuation errors, but including valuation shocks
            EbidderW_obj_unb_mat(i,k) = nanmean(bidder_value_obj_unb_vec)/n_bidders_all_vec(i); % expected surplus, excluding valuation errors and valuation shock

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            Ebidders_mat(i,k)         = nanmean(nbidders_vec)/n_bidders_all_vec(i); % expected share of bidders entering the auction
            Psales_mat(i,k)           = sum(sales_succ_vec)/n_sim; % sales probability           
            Esales_mat(i,k)           = nanmean(sales_price_vec)-seller_reservation; % expected sales price - seller reservation values
            Erev_mat(i,k)             = Psales_mat(i,k)*Esales_mat(i,k);  % expected seller revenue           

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        
        
        end
    
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    delete(poolobj);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Save

    save([save_str,'\Output\Last\EndowBiasInd\equilibrium_step1_last_endow_mu',num2str(grid_mat(bb,1)*100),'_biasstd',num2str(grid_mat(bb,2)*100),'.mat']);
    
    grid_mat(bb,:)

    clearvars -except grid_mat n_grid bb main_str save_str

end

